package com.acxy.ants.resful.render;

import com.acxy.ants.common.kit.FileKit;
import com.acxy.ants.core.Const;
import com.acxy.ants.core.config.Modules;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-08-29
 */
public class Resource {

    private static final Logger logger = LoggerFactory.getLogger(Resource.class);

    //jar下面的资源路径
    private String resName;

    //填充的数据
    private Object data;

    public Resource(String resName) {
        this.resName = resName;
    }

    public Resource(String resName, Object data) {
        this.resName = resName;
        this.data = data;
    }


    public void render(HttpServletRequest request, HttpServletResponse response) {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resName);
        write(request, response, in);
    }

    public void render(String errorPage, String moduleName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream in = null;
        //本身目录
        if (moduleName == null)
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resName);
        else
            //是否设置缓存, 最后一个参数代表启动缓存
            in = Modules.getModuleResInputStream(moduleName, resName);
        String ctx = request.getContextPath();
        if (in == null) {
            if (errorPage != null) response.sendRedirect(ctx + errorPage);
            if (moduleName == null)
                logger.debug("提示: 项目资源目录中 " + resName + " 文件不存在!");
            else
                logger.debug("提示: [" + moduleName + "] 模块中 " + resName + " 文件不存在!");
            return;
        }
        write(request, response, in);
    }

    public void write(HttpServletRequest request, HttpServletResponse response, InputStream in) {
        try {
            String text = "";
            Map<String, Object> dataMap = null;
            if (resName.endsWith(".html") || resName.endsWith(".htm")) {
                response.setContentType("text/html; charset=utf-8");
                dataMap = new HashMap<>();
                dataMap.put("ctx", request.getContextPath());
                dataMap.put("JS_PATH", "/static/js");
                dataMap.put("IMG_PATH", "/static/images");
                dataMap.put("CSS_PATH", "/static/css");
                dataMap.put("SWF_PATH", "/static/swf");
                dataMap.put("UE_PATH", "/static/ueditor");
                //处理简单数据模板填充
                if (data != null && data instanceof Map) {
                    dataMap.putAll((Map) data);
                }
            } else if (resName.endsWith(".jpg") || resName.endsWith(".png") || resName.endsWith(".gif")) {
                response.setContentType("image/*");
                int i = in.available();
                //byte数组用于存放图片字节数据
                byte[] buff = new byte[i];
                in.read(buff);
                //记得关闭输入流
                in.close();
                OutputStream out = response.getOutputStream();
                out.write(buff);
                //关闭响应输出流
                out.close();
                return;
            } else if (resName.endsWith(".css")) {
                response.setContentType("text/css;charset=utf-8");
            } else if (resName.endsWith(".js")) {
                response.setContentType("text/javascript;charset=utf-8");
            } else if (resName.endsWith(".xml")) {
                response.setContentType("text/xml;charset=utf-8");
            } else if (resName.endsWith(".doc")) {
                response.setContentType("application/msword;charset=utf-8");
            } else if (resName.endsWith(".pdf")) {
                response.setContentType("application/pdf;charset=utf-8");
            } else if (resName.endsWith(".zip")) {
                response.setContentType("application/zip;charset=utf-8");
            } else {
                response.setContentType("*/*;charset=utf-8");
            }
            text = FileKit.read(in, Const.DEFAULT_ENCODING);
            if (dataMap != null) text = replace(text, dataMap);
            response.getWriter().write(text);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据键值对填充字符串
     *
     * @param content
     * @param map
     * @return
     */
    private String replace(String content, Map<String, Object> map) {
        Set<Map.Entry<String, Object>> sets = map.entrySet();
        for (Map.Entry<String, Object> entry : sets) {
            String key = entry.getKey();
            String regex = "${" + key + "}";
            content = content.replace(regex, String.valueOf(entry.getValue()));
        }
        return content;
    }
}
